package com.system.util.freemarker.template;

import com.alibaba.fastjson.JSON;
import com.component.domain.MMenu;
import com.component.domain.SysMenuEntity;
import com.component.domain.SysRoleMenuEntity;
import com.component.service.MMenuService;
import com.component.service.SysRoleMenuService;
import com.system.config.freemarker.DirectiveHandler;
import com.system.config.freemarker.FreemarkerScan;
import com.system.config.freemarker.TemplateDirective;
import com.system.security.SecurityUtil;
import com.system.security.domain.SelfUserEntity;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Classname MenuParentTemplate
 * @Description TODO
 * @Date 2023/9/28 16:30
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@FreemarkerScan("menuparent")
public class MenuParentTemplate extends TemplateDirective {

    @Autowired
    private MMenuService mMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Override
    public String getName() {
        return "menuparent";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {
        SelfUserEntity userEntity=SecurityUtil.getSelfUserEntity();
        List<SysRoleMenuEntity> list=sysRoleMenuService.getSysRoleMenuEntityUid(userEntity.getUserId());
        List<MMenu> menuList=null;
        if(list != null && list.size() > 0){
            List<Integer> ids=list.stream().map(e->Integer.valueOf(String.valueOf(e.getMenuId()))).collect(Collectors.toList());
            List<MMenu> menuLists=mMenuService.getMMenuList(ids);
            if(menuLists != null && menuLists.size() > 0){
                menuList=menuLists.stream().filter(e->e.getParent()!=null).map(MMenu::getParent).distinct().collect(Collectors.toList());
            }
        }
        if(menuList==null){
            menuList= Collections.emptyList();
        }
        System.out.println(userEntity.getUsername()+" username");

        Map<String, Object> map = new HashMap<>();
        map.put("records", menuList);
        handler.put(RESULTS,map).render();
    }
}
